/*
 * Scale.cpp
 *
 *  Created on: Dec 21, 2011
 *      Author: quotrader
 */

#include "Scale.h"
#include <sys/neutrino.h>

Scale::Scale() {
	this->setupTime();
	finishAll=false;
	nextPeriod=0;

}

void Scale::start() {
	this->startTime= this->getRelTime();
	this->startUnitTime= this->getUniTime();
}


void Scale::setupTime() {

	// change the original time base from 1 ms to be 5 ms
	struct _clockperiod n;
	struct _clockperiod o;

	// 1 ms
	n.nsec = 999847;
	n.fract = 0;

	// Original time base is 1ms 999847:0
	ClockPeriod(CLOCK_REALTIME, &n, &o, NULL);
}


timespec Scale::getRelTime() {
	timespec t;
	clock_gettime(CLOCK_REALTIME, &t);
	return t;
}


void Scale::humanTime(char *buff,timespec t) {
	time_t seconds = t.tv_sec;
	ctime_r(&seconds, buff);
}


unitTime Scale::getUniTime() {
	timespec now,diff;
	struct unitTime tmp;
	now= this->getRelTime();

	diff.tv_sec= now.tv_sec - this->startTime.tv_sec;
	diff.tv_nsec= now.tv_nsec - this->startTime.tv_nsec ;

	if(diff.tv_nsec < 0) {
		diff.tv_sec--;
		diff.tv_nsec=diff.tv_nsec+1000000000;
	}

	tmp.unit= (diff.tv_sec*1000)/5;
	tmp.subUnit=diff.tv_nsec/1000000;
	if(tmp.subUnit > 5){
		tmp.unit+=(tmp.subUnit/5);
		tmp.subUnit=(tmp.subUnit%5)*1000000;
	}
	return tmp;
}

timespec Scale::getSmallestUnit() {
	timespec t;
	t.tv_nsec=5000000;
	t.tv_sec=0;
	return t;
}

/*
 * 	timespec intr;
 sched_rr_get_interval(getpid(),&intr);*/
